<template>
    <div class="searchGoods">
        <nut-searchbar 
            v-model="searchValue"
            @clear="SearchClear">
            <template v-slot:rightout >
                <p @click="SearchClick">搜索</p>
            </template>
        </nut-searchbar>
        <div class="content" v-if="searchResultList.length">
            <template  v-for="(item, idx) in searchResultList" :key="idx" >
                <div class="goods" @click="GoGoodsDetails(item)">      
                    <div class="goods-photo">
                      <Image class="goods-photo-img" :src="item?.bannerImgs[0]"></Image>
                    </div>
                    <div class="goods-message">
                      <p>{{ item.name }}</p>
                    </div>
                    <div class="goods-priceAndNum">
                        <p >¥ {{ item.price }}</p>
                    </div>
                </div>
            </template>
        </div>
        <nut-empty description="无数据" v-else></nut-empty>
    </div>
  </template>
  
<script>
import { onMounted, reactive, toRefs } from 'vue';
import './index.scss';
import { GetTagList,SearchGoods } from '../utils/api.js' 
import Taro from '@tarojs/taro'
export default {
    name: 'searchGoods',
    components: {
    },
    setup(){
        const state = reactive({
            searchValue: '',
            tagList: [],
            searchResultList: [],
        });
        const GetTag = async () => {
            let tagRes = await GetTagList({});
            if(tagRes.code == 200) {
                state.tagList = tagRes.data.list;
            } 
        }
        onMounted(() => {
            GetTag();
        })
        const SearchClick = async () => {
            let resultObj = state.tagList.find(i => i.name.includes(state.searchValue));
            let searchRes = await SearchGoods({
                name: state.searchValue,
                categoryId: resultObj == undefined ? undefined : resultObj.code
            });
            if(searchRes.code == 200) {
                state.searchResultList = searchRes.data.list;
            }
        }
        const SearchClear = () => {
            state.searchResultList = []
        }
        const GoGoodsDetails = (tarGoodsVal) => {
            Taro.navigateTo({
                url: `/pages/commodity-details/index?commodityId=${tarGoodsVal.id}`
            })
        }
        return {
            SearchClick,
            SearchClear,
            GoGoodsDetails,
            ...toRefs(state),
        }
    }
}
</script>
  
  